import router from '@/router'
// 引入进度条和样式
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store'

router.beforeEach(async (to, from, next) => {
  Nprogress.start()
  if (store.state.user.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (store.state.user.userInfo.name) {
        next()
      } else {
        try {
          await store.dispatch('user/getUserInfo')
          next()
        } catch (error) {
          // token失效
          await store.dispatch('user/userLogout')
          next('/login')
        }
      }
    }
  } else {
    next()
  }
  Nprogress.done()
})

router.afterEach((to, from) => {
  Nprogress.done()
})
